{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 信息增益计算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import log\n",
    "from collections import Counter\n",
    "from functools import reduce "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "outlook = {'sunny':[1,1,0,0,0],'overcast':[1,1,1,1],'rainy':[1,1,1,0,0]}\n",
    "humidity = {'high':[1,1,1,0,0,0,0],'normal':[1,1,1,1,1,1,0]}\n",
    "windy = {'windy_false':[1,1,1,1,1,1,0,0],'windy_true':[1,1,1,0,0,0]}\n",
    "temperature = {'hot':[1,1,0,0],'mild':[1,1,1,1,0,0],'cool':[1,1,1,0]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def calcShannonEnt(dataSet):\n",
    "    numEntries = len(dataSet)\n",
    "    counter = Counter(dataSet)\n",
    "    shannonEnt = 0.0\n",
    "    for key in counter.keys():\n",
    "        prob = float(counter[key]) / numEntries\n",
    "        shannonEnt -= prob * log(prob,2)\n",
    "    return shannonEnt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def calcInfoGain(dataSet):\n",
    "    numEntries = sum(len(x) for x in dataSet.values())\n",
    "    baseEntropy = calcShannonEnt(reduce(lambda x,y:x+y,dataSet.values()))\n",
    "    newEntropy = 0.0\n",
    "    for value in dataSet.values():\n",
    "        prob = len(value) / float(numEntries)\n",
    "        newEntropy += prob * calcShannonEnt(value)\n",
    "    infoGain = baseEntropy - newEntropy\n",
    "    return infoGain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "outlook 信息增益： 0.2467498197744391\n",
      "humidity 信息增益： 0.15183550136234136\n",
      "windy 信息增益： 0.04812703040826927\n",
      "temperature 信息增益： 0.029222565658954647\n"
     ]
    }
   ],
   "source": [
    "print('outlook 信息增益：',calcInfoGain(outlook))\n",
    "print('humidity 信息增益：',calcInfoGain(humidity))\n",
    "print('windy 信息增益：',calcInfoGain(windy))\n",
    "print('temperature 信息增益：',calcInfoGain(temperature))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# outlook属性对应的信息增益最大"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
